<?php

namespace fast;

use GuzzleHttp\Client;
use think\Exception;

/**
 * 阿里云快递鸟Api
 * Class ExpressBird
 * @package fast
 */
class ExpressBird
{

    /**
     * 快递鸟api appKey
     * @var string
     */
    protected $appKey = '204618677';

    /**
     * 快递鸟api appSecret
     * @var string
     */
    protected $appSecret = '7shSzpINgeXSBViGOHCBxlEieEeecdcO';

    /**
     * 快递鸟api appCode
     * @var string
     */
    protected $appCode = '76d1e0a17ae24a2fa3d90a97580bc0aa';

    /**
     * 接口域名
     * @var string
     */
    protected $host = 'https://alicloudmarket8002.kdniao.com';

    /**
     * GuzzleHttp客户端实例化
     * @var \GuzzleHttp\Client
     */
    protected $client;

    public function __construct()
    {
        $this->client = new Client([
            // 关闭错误异常
            'http_errors' => false,
            // 关闭所有异常
            'exceptions'  => false,
            // 接口域名
            'base_uri'    => $this->host,
        ]);
    }

    /**
     * 查询快递轨迹
     * @param $logisticCode
     * @param int $phone
     * @return mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function queryTrack($logisticCode, $phone)
    {
        $uri = '/api/track/8002';
        // 请求参数
        $data = [
            'CustomInfo'   => 0000,
            'LogisticCode' => $logisticCode
        ];

        // 如果是顺丰需要加入尾号参数
        if (strpos($logisticCode, 'SF') !== false) {
            // 获取尾号
            $lastNumber           = substr($phone, 7, 4);
            $data['CustomerName'] = $lastNumber;
        }

        $res = $this->client->request('POST', $uri, [
            'headers' => [
                'Authorization' => 'APPCODE ' . $this->appCode,
                'Content-Type'  => 'application/json; charset=UTF-8'
            ],
            'json'    => $data
        ])->getBody()->getContents();

        $res = json_decode($res, true);

        if (!empty($res['Reason'])) {
            $res['Traces'] = [];
        }

        return $res;
    }
}